<template>
  <div class="chuantu flexcc" style="position: relative;">
    <div v-if="fonttype=='fonttype'">
      <el-upload  action="#" :on-change="uploadok" :auto-upload="false" :show-file-list="false">
        <el-button type="text">上传图片</el-button>
      </el-upload>

    </div>
    <div v-else>
      <el-upload  class="avatar-uploader " :style="tubiaocss" action="#" :on-change="uploadok" :auto-upload="false" :show-file-list="false">
        <img v-if="img" :src="img" class="avatar chuantu" >
        <div style="position: absolute; left:1px;bottom:0;line-height: 35px; background:rgba(0,0,0,0.5); color:#fff;  width:100%; border-radius:3px; text-align:center;" class="genghuan">点击图片更换</div>
        <i v-if="!img" v-else class="el-icon-plus avatar-uploader-icon" :style="tubiaocss"></i>
      </el-upload>
      <el-button v-if="img" size="medium" style="height: 40px; margin-left: 20px;"  @click="shanchu" type="text">删除</el-button>
    </div>
    
  </div>
</template>

<script>
  import * as qiniu from 'qiniu-js'
  import axios from "axios";
  export default {
    name: 'chuantu',
    props:['imgs','widths','heights','shows','fonttype'],
    data() {
      return {
        img: "",
        show:false,
      }
    },
    created() {

      if(this.imgs){
        console.log('haibaoImg1111',this.imgs)
        this.img = this.imgs
      }

      if(!this.widths){
        this.widths = '194px'
      }
      if(!this.heights){
        this.heights = '194px'
      }
      this.tubiaocss = {
        width:this.widths,
        maxHeight:this.heights,
        lineHeight:this.heights
      }
    },
    methods: {
      shanchu:function(){
        this.img = ''
        this.$emit('getimg', '')
      },

      dataURLtoFile(dataurl, filename) {
        let arr = dataurl.split(","),
          mime = arr[0].match(/:(.*?);/)[1],
          bstr = atob(arr[1]),
          n = bstr.length,
          u8arr = new Uint8Array(n);
        while (n--) {
          u8arr[n] = bstr.charCodeAt(n);
        }
        return new File([u8arr], filename, {
          type: mime
        });
      },
      //单个图片上传
      uploadok: function(file) {
        //  console.log("111",file);
        let wenjianjia = 'img'
        let name = new Date().getTime()

        if(process.env.NODE_ENV === 'development'){
          wenjianjia = 'test-img'
        }
        if(window.location.href.includes('storep.91haoka.cn') && this.apis == ''){
          wenjianjia = 'img'
        }
        if(window.location.href.includes('store.91haoka.cn') && this.apis == ''){
          wenjianjia = 'test-img'
        }
        let type = file.raw.type.split('/')

        axios.post(`${this.apis}/api/qiniu/token`,{bucket:'gthshopstore',cloud:`${wenjianjia}/${name}.${type[1]}`})
          .then(response => {
            var that = this
            console.log('response.data',response.data)
            if(response.data.msg.code == 0){
              const observer = {
                next(res){
                  console.log("1111",res)
                
                },
                error(err){
                   console.log("2222",err)      
                },
                complete(res){
                  console.log("333",res)
                  that.img = 'https://file.storep.91haoka.cn/' + res.key
                  that.$emit('getimg', 'https://file.storep.91haoka.cn/' + res.key)
                }
              }
              const options = {
                quality: 1,
                noCompressIfLarger: true,
                maxWidth: 1920
              }

              
              //之前的逻辑
              // qiniu.compressImage(file.raw, options).then(data => {
              //   console.log("data",data);
              //   const observable = qiniu.upload(data.dist, `${wenjianjia}/${name}.${type[1]}`, response.data.data)
              //   const subscription = observable.subscribe(observer) // 上传开始
              // })

             
              // 现在的逻辑
                const observable = qiniu.upload(file.raw, `${wenjianjia}/${name}.${type[1]}`, response.data.data,{}, {})
                const subscription = observable.subscribe(observer) // 上传开始



                
            }else{
              this.$message.error(response.data.msg.info);
            }
          });


        // var that = this;
        // var reader = new FileReader()
        // var img = new Image();
        // reader.onload = function(e) {
        //   img.src = e.target.result;
        // };
        // var canvas = document.createElement('canvas');
        // var context = canvas.getContext('2d');
        // // base64地址图片加载完毕后
        // let p = new Promise((r, j) => {
        //   img.onload = function() {
        //     // 图片原始尺寸
        //     var originWidth = this.width;
        //     var originHeight = this.height;
        //     // 最大尺寸限制
        //     var maxWidth = 1920,
        //       maxHeight = 10000;
        //     // 目标尺寸
        //     var targetWidth = originWidth,
        //       targetHeight = originHeight;
        //     // 图片尺寸超过400x400的限制
        //     if (originWidth > maxWidth || originHeight > maxHeight) {		              if (originWidth / originHeight > maxWidth / maxHeight) {
        //          // 更宽，按照宽度限定尺寸                  targetWidth = maxWidth;                  targetHeight = Math.round(maxWidth * (originHeight / originWidth));
	       //        } else {                  targetHeight = maxHeight;
        //          targetWidth = Math.round(maxHeight * (originWidth / originHeight));		              }
        //     }
        //     // canvas对图片进行缩放
        //     canvas.width = targetWidth;
        //     canvas.height = targetHeight;
        //     // 清除画布
        //     context.clearRect(0, 0, targetWidth, targetHeight);
        //     // 图片压缩
        //     context.drawImage(img, 0, 0, targetWidth, targetHeight);

        //     let base64 = canvas.toDataURL("image/jpeg", 0.8); // 压缩后的base64图片
        //     let file2 = that.dataURLtoFile(base64, Date.parse(Date()) + ".jpg");		            r(file2)
        //   };
        // })
        // reader.readAsDataURL(file.raw);
        // p.then(files => {
        //   var formData = new FormData();
        //   formData.append("file", files);
        //   formData.append("type", 'pic');
        //   axios.post(`${this.apis}/api/system/upload`, formData)
        //     .then(response => {
        //       if (response.data.msg.code == 0) {
        //         that.img = response.data.data
        //         that.$emit('getimg', response.data.data)
        //       } else {
        //         that.$message.error(response.data.msg.info);
        //       }
        //     })
        // })
      }

    }
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="less">

    .avatar-uploader{
    	border: 1px dashed #d9d9d9;
    	border-radius: 6px;
    	cursor: pointer;
    	position: relative;
    	overflow: hidden;
      /deep/ .el-upload{ display: block;}
    }

    .avatar-uploader .el-upload:hover {
    	border-color: #409EFF;
    }

    .avatar-uploader-icon {
    	font-size: 28px;
    	color: #8c939d;

    	text-align: center;
    }

    .avatar {
    	// max-width: 194px;
    	// max-height: 194px;
    	display: block;
      img{width: 100%; display: block;}
    }
    .genghuan{ display: none;}
    .chuantu:hover{
      .genghuan{ display: block;}
    }
</style>
